package com.wk.springboot.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Classname LoginController
 * @Description login的controller
 * @Date 2020/5/19 14:58
 * @Author by weikai
 */

@Controller
public class LoginController {

  private static transient final Logger log = LoggerFactory.getLogger(LoginController.class);

  @RequestMapping(value = "/login", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
  public String login(@RequestParam("userName") String userName,
      @RequestParam("passWord") String passWord) {

    //获取当前用户信息
    Subject subject = SecurityUtils.getSubject();

    //判断subject登录信息
    boolean isLog = false;
    if (subject != null && subject.isAuthenticated()) {
      isLog = true;
    }

    if (isLog) {
      subject.logout();
    }

    //包装用户名和密码，封装成 UsernamePasswordToken对象
    UsernamePasswordToken token = new UsernamePasswordToken(userName, passWord);
    token.setRememberMe(true);

    try {
      subject.login(token);
    } catch (AuthenticationException e) {
      log.debug("Error authenticating.", e);
      throw new AuthenticationException();
    }

    return "hello";
  }

  @RequiresGuest
  @RequestMapping("/guest")
  @ResponseBody
  public String guest() {
    //获取当前用户信息
    Subject subject = SecurityUtils.getSubject();
    return "guest";
  }

  @RequiresUser
  @RequestMapping("/user")
  @ResponseBody
  public String user() {
    //获取当前用户信息
    Subject subject = SecurityUtils.getSubject();
    return "user";
  }
}
